/**
 * Copyright (c) 2015-2018, Golly Hu 胡高 (3722711@qq.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.hg.jfsa.core.option;

import cn.hg.base.kit.StrExtKit;
import com.jfinal.log.Log;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Golly
 *
 */
public class Options {
	private static final Log LOG = Log.getLog(Options.class);
	private static final Map<String, Object> options = new ConcurrentHashMap<>();
	private static final List<OptionChangeListener> LISTENERS = new ArrayList<>();

	public static void set(String key, String value) {
		if (StrExtKit.isBlank(key)) {
			return;
		}

		String oldValue = (String) options.get(key);
		if (Objects.equals(value, oldValue)) {
			return;
		}

		options.put(key, value);

		for (OptionChangeListener listener : LISTENERS) {
			try {
				listener.onChanged(key, value, oldValue);
			} catch (Throwable ex) {
				LOG.error(ex.toString(), ex);
			}
		}
	}

	public static String get(String key) {
		return (String) options.get(key);
	}

	public static boolean getAsBool(String key) {
		return Boolean.parseBoolean((String) options.get(key));
	}

	public static int getInt(String key, int defaultValue) {
		String value = get(key);
		if (StrExtKit.isBlank(value)) {
			return defaultValue;
		}
		return Integer.parseInt(value);
	}

	public static float getFloat(String key, float defaultValue) {
		String value = get(key);
		if (StrExtKit.isBlank(value)) {
			return defaultValue;
		}
		return Float.parseFloat(value);
	}

	public static Map<String, Object> getAll() {
		return options;
	}

	public static void addListener(OptionChangeListener listener) {
		if (LISTENERS.contains(listener)) {
			return;
		}
		LISTENERS.add(listener);
	}

	public static void removeListener(OptionChangeListener listener) {
		LISTENERS.remove(listener);
	}

	public static interface OptionChangeListener {
		public void onChanged(String key, String newValue, String oldValue);
	}

}
